#!/bin/bash

image=$1
tag=$2

manifests=$(docker buildx imagetools inspect $image:$tag --raw)

imagePath="/tmp/$image"
mkdir -p "$imagePath"

imageName=${image##*/}
echo "package save at $imagePath"
echo "start package image $image:$tag"

for i in $(seq 0 $(echo $manifests | jq '.manifests|length'-1)); do
  arch=$(jq -r .manifests[$i].platform.architecture <<<$manifests)
  digest=$(jq -r .manifests[$i].digest <<<$manifests)

  rm -rf "$imagePath/$imageName.tar.gz-$arch-$tag"

  echo "package $imagePath/$imageName.tar.gz-$arch-$tag ..."

  docker rmi "$image:$arch-$tag"
  docker pull --platform="$arch" "$image@$digest"
  docker tag "$image@$digest" "$image:$arch-$tag"
  docker save "$image:$arch-$tag" -o "$imagePath/$imageName.tar.gz-$arch-$tag"
  docker rmi $image:$arch-$tag

done
